import React, { Component, Fragment } from "react";
// antd
import { Modal, Table, Button, Col, Pagination, Form, Input, message, Select, Tag, Switch } from "antd";
import Action from "@c/buttonAction/Index";
// http
import http from '../../utils/request';

const { Option } = Select;
const { TextArea } = Input;

class NotifyAdminMessageManage extends Component {
    constructor(props){
        super(props);
        this.state = {
            // 表格分页
            total: '',
            page: 1,
            page_number: 10,
            dataSource: [],
            columns: [
                {title: "消息名称", dataIndex: "remark", key: "remark"},
                {title: "消息类型", dataIndex: "message_type", key: "message_type"},
                {title: "消息内容", dataIndex: "message", key: "message"},
                {title: "创建人", dataIndex: "user_name", key: "user_name"},
                {title: "消息群", dataIndex: "notify_admin_group", key: "notify_admin_group",
                    render: (text, rowData) => {
                        var tag_style = {float: 'left', margin: '2px'}
                        return(
                            <div>
                                {
                                rowData.notify_admin_group_list.map(group_title => (
                                    <div style={tag_style}><Tag key={group_title} color="processing">{group_title}</Tag></div>
                                ))
                                }
                            </div>
                        )
                    }            
                },
                {title: "开关", dataIndex: "alarm_status", key: "alarm_status",
                    render: (text, rowData) => {
                        return (
                            <Switch 
                                size="small" 
                                defaultChecked={rowData.alarm_status} 
                                onClick={() => this.onChangeAlarmStatus(rowData.id)} 
                            />
                        )
                    }
                },
                {title: "操作", dataIndex: "operation", key: "operation", 
                    render: (text, rowData) => {
                        return (
                            <div className="inline-button">
                                <Action>
                                    <Action.Button onClick={() => this.onEditNotifyAdminGroupMessageBtn({rowData: rowData, status: true})}>编辑</Action.Button>
                                    <Action.Button onClick={() => this.onDeleteNotifyAdminGroupMessageBtn(rowData)}>删除</Action.Button>
                                    <Action.Button onClick={() => this.onSendMessageBtn({rowData: rowData})}>发送钉钉消息</Action.Button>
                                </Action>
                            </div>

                        )
                    }           
                }
            ],
            loading: false,
            visible_add: false,      // 添加
            visible_edit: false,     // 编辑
            visible_delete: false,   // 删除
            visible_send_msg: false, // 发送消息
            visible_edit_id: '',
            visible_edit_name: '',
            visable_edit_code: '',
            message_id: '',
            search_cloud_platform_name: '',
            search_option_notify_admin_group: [], //钉钉消息
            search_alarm_status: null
        }
        this.formRefAdd = React.createRef();
        this.formRefEdit = React.createRef();
        this.formRefSendMsg = React.createRef();
    }

    componentDidMount() {
        this.loadData()
        this.loadNotifyAdminGroup()
    }

    loadData = () => {
        this.setState({
            loading: true
        })
        const requestData = {
            'page': this.state.page,
            'limit': this.state.page_number,
            'message__contains': this.state.search_message,
            'alarm_status': this.state.search_alarm_status,
        }

        // 获取列表
        http.get('/notify/admin/message', {params: requestData}).then(response=>{
            this.setState({
                dataSource: response.data.data.items,
                total: response.data.data.pages.total,
                loading: false
            })
        }).catch()
    }

    loadNotifyAdminGroup = () => {
        const requestData = {
            'page': 1,
            'limit': 1000,
        }
        http.get('/notify/admin/group', {params: requestData}).then(response=>{
            const search_option_notify_admin_group = []
            const resp_data = response.data.data.items
            for (let i = 0; i < resp_data.length; i++) {
                search_option_notify_admin_group.push(<Option key={resp_data[i].id}>{resp_data[i].group_title}</Option>)
            }
            this.setState({
                search_option_notify_admin_group: search_option_notify_admin_group
            })
        })
    }

    /** 切换每页数量 */
    onChangeSizePage = (page, page_number) => {
        this.setState({
            page: page,
            page_number: page_number,
        }, () => {
            this.loadData()
        })
    }

    /** 搜索 */
    onFinishSearch = (data) => {
        this.setState({
            page: 1,
            search_message: data.message ? data.message : null,
            search_alarm_status: data.alarm_status ? data.alarm_status : null,
        })
        this.loadData()
    }

    /** 添加按钮 */
    onAddNotifyAdminGroupMessageBtn = () => {
        this.setState({
            visible_add: true
        })
    }

    /** 添加取消 */
    onFinishAddCancel = () => {
        this.setState({
            visible_add: false
        })
        this.formRefAdd.current.resetFields()
    }

    /** 添加提交 */
    onFinishAdd = (data) => {
        const requestData = {
            message: data.message,
            message_type: data.message_type,
            remark: data.remark,
            notify_admin_group_ids: data.notify_admin_group_ids
        }
        http.post('/notify/admin/message', requestData).then(response=>{
            message.success(response.data.msg)
            this.setState({
                visible_add: false,
            })
            this.formRefAdd.current.resetFields()
            this.loadData()
        }).catch()
    }

    /** 发送按钮 */
    onSendMessageBtn = (data) => {
        http.get('/notify/admin/message').then(response=> {
            this.formRefSendMsg.current.setFieldsValue({
                id: data.rowData.id,
                remark: data.rowData.remark,
                message: data.rowData.message,
                notify_admin_group_ids: data.rowData.notify_admin_group_ids
            })
        })
        
        this.setState({
            visible_send_msg: true,
        })
    }

    /** 发送消息取消 */
    onFinishMessageSendCancel = () => {
        this.setState({
            visible_send_msg: false,
        })
        this.formRefSendMsg.current.resetFields();
    }

    /** 发送消息提交 */
    onFinishMessageSend = (data) => {
        this.formRefSendMsg.current.resetFields()
        this.setState({
            loading_label: true
        })
        const requestData = {
            notify_admin_group_ids: data.notify_admin_group_ids,
            operation_type: 'send_dintalk_msg',
        }
        http.patch('/notify/admin/message/' + data.id, {params: requestData}).then(response=>{
            message.success(response.data.msg)
            this.setState({
                loading_label: false,
                visible_send_msg: false,
                selectedRowKeys: [],
            })
            this.loadData()
        })
    }

    /** 编辑按钮 */
    onEditNotifyAdminGroupMessageBtn = (data) => {
        http.get('/notify/admin/message').then(response=> {
            this.formRefEdit.current.setFieldsValue({
                id: data.rowData.id,
                remark: data.rowData.remark,
                message: data.rowData.message,
                message_type: data.rowData.message_type,
                notify_admin_group_ids: data.rowData.notify_admin_group_ids
            })
        })
        
        this.setState({
            visible_edit: true,
        })
    }

    /** 编辑取消 */
    onFinishEditCancel = () => {
        this.setState({
            visible_edit: false,
        })
        this.formRefEdit.current.resetFields();
    }

    /** 编辑提交 */
    onFinishEdit = (data) => {
        const requestData = {
            message: data.message,
            message_type: data.message_type,
            remark: data.remark,
            notify_admin_group_ids: data.notify_admin_group_ids
        }
        http.put('/notify/admin/message/' + data.id, requestData).then(response=>{
            message.success(response.data.msg)
            this.setState({
                visible_edit: false
            })
            this.formRefEdit.current.resetFields();
            this.loadData()
        }).catch()
    }

    /** 删除提交 */
    handleNotifyAdminGroupMessageDelete = () => {
        http.delete('/notify/admin/message/' + this.state.message_id).then(response=>{
            message.success(response.data.msg)
            this.setState({
                visible_delete: false,
            })
            this.loadData()
        }).catch()    
    }

    /** 删除按钮 */
    onDeleteNotifyAdminGroupMessageBtn = (data) => {
        this.setState({
            message_id: data.id,
            visible_delete: true
        })
    }

    /** 开关按钮 */
    onChangeAlarmStatus = (id) => {
        const requestData = {
            instance_id: id,
            operation_type: 'change_alarm_status',
        }
        http.patch('/notify/admin/message', {params: requestData}).then(response=>{})
    }

    render(){
        const { loading, dataSource, columns, page, total, visible_add, visible_edit, visible_delete, visible_send_msg, search_option_notify_admin_group } = this.state
        var myStyle = {margin: '20px'}
        var myStyle1 = {margin: '10px', float: 'right'}
        var myStyleForm = {marginRight: '10px', marginTop: '5px'}

        return (
            <Fragment>
                <Form layout="inline" onFinish={this.onFinishSearch}>
                    <Form.Item label="消息内容" name="message">
                        <Input placeholder="请输入消息内容"  />
                    </Form.Item>

                    <Form.Item label="消息类型" name="message_type">
                        <Input placeholder="请输入消息类型"  />
                    </Form.Item>

                    <Form.Item label="消息状态" name="alarm_status" size="small">
                        <Select
                            allowClear
                            showSearch
                            style={{ width: 200 }}
                            placeholder="查询消息状态"
                            >
                            <Option key={false}>禁用</Option>
                        </Select>                      
                    </Form.Item>

                    <Form.Item shouldUpdate={true}>
                        <Button type="primary" htmlType="submit">搜索</Button>
                    </Form.Item>
                </Form>
                
                {/* <div style={myStyle1}><Button type="primary" onClick={this.onAddNotifyAdminGroupMessageBtn}>添加钉钉消息</Button></div> */}
                <div style={myStyle1}>
                    <Action.Button onClick={this.onAddNotifyAdminGroupMessageBtn}>添加钉钉消息</Action.Button>
                </div>

                <Table
                    pagination={false} 
                    // rowSelection={rowSelection} 
                    rowKey="id" 
                    columns={columns} 
                    dataSource={dataSource}
                    loading={loading}
                    scroll={{ y: 500, x: '70vw' }}
                >
                </Table>

                <div style={myStyle}>
                    <Col span={16}>
                        <Pagination
                            onChange={this.onChangeSizePage}
                            current={page}
                            total={total}
                            showSizeChanger
                            showQuickJumper
                            showTotal={total => `Total ${total} items`}
                        />
                    </Col>
                </div>

                <Modal
                    title="添加钉钉消息"
                    visible={visible_add}
                    onCancel={this.onFinishAddCancel}
                    okText="确认"
                    cancelText="取消"
                    footer={null}
                    width={1000}
                >
                    <Form
                        onFinish={this.onFinishAdd}
                        ref={this.formRefAdd}
                    >
                        <Form.Item label="消息名称" name="remark" rules={[{ required: true}]}>
                            <Input></Input>
                        </Form.Item>

                        <Form.Item label="消息类型" name="message_type" rules={[{ required: true}]}>
                            <Select
                                allowClear
                                showSearch
                                style={{ width: '100%' }}
                                placeholder="选择消息类型"
                            >
                                <Option key='text'>文本消息</Option>
                                <Option key='markdown'>Markdown</Option>
                            </Select>
                        </Form.Item>

                        <Form.Item label="消息群组" name="notify_admin_group_ids" rules={[{ required: true}]} style={myStyleForm}>
                            <Select
                                allowClear
                                showSearch
                                mode="multiple"
                                // style={{ width: 180 }}
                                placeholder="请选择消息群"
                                optionFilterProp="children"
                                onChange={this.onChangePlatform}
                                filterOption={(input, option) =>
                                    option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                }
                            >
                                {search_option_notify_admin_group}
                            </Select>
                        </Form.Item>

                        <Form.Item label="消息内容" name="message" rules={[{ required: true}]}>
                            <TextArea rows={20} placeholder="请输入消息内容" />
                        </Form.Item>      

                        <Form.Item>
                            <Button htmlType="submit" type="primary">确定</Button>
                        </Form.Item>                                                               
                    </Form>           
                </Modal>

                <Modal
                    title="编辑钉钉消息"
                    visible={visible_edit}
                    onCancel={this.onFinishEditCancel}
                    okText="确认"
                    cancelText="取消"
                    footer={null}
                >
                    <Form
                        onFinish={this.onFinishEdit}
                        ref={this.formRefEdit}
                    >
                        <Form.Item label="消息ID" name="id" hidden style={myStyleForm}>
                            <Input ></Input>
                        </Form.Item>

                        <Form.Item label="消息名称" name="remark" rules={[{ required: true}]} style={myStyleForm}>
                            <Input disabled></Input>
                        </Form.Item>

                        <Form.Item label="消息类型" name="message_type" rules={[{ required: true}]} style={myStyleForm}>
                            <Select
                                allowClear
                                showSearch
                                style={{ width: '100%' }}
                                placeholder="选择消息类型"
                            >
                                <Option key='text'>文本消息</Option>
                                <Option key='markdown'>Markdown</Option>
                            </Select>
                        </Form.Item>

                        <Form.Item label="消息群组" name="notify_admin_group_ids" rules={[{ required: true}]} style={myStyleForm}>
                            <Select
                                allowClear
                                showSearch
                                mode="multiple"
                                // style={{ width: 180 }}
                                placeholder="请选择消息群"
                                optionFilterProp="children"
                                onChange={this.onChangePlatform}
                                filterOption={(input, option) =>
                                    option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                }
                            >
                                {search_option_notify_admin_group}
                            </Select>
                        </Form.Item>

                        <Form.Item label="消息内容" name="message" rules={[{ required: true}]} style={myStyleForm}>
                            <TextArea rows={20} placeholder="请输入消息内容" />
                        </Form.Item>

                        <Form.Item>
                            <Button htmlType="submit" type="primary">确定</Button>
                        </Form.Item>                                                               
                    </Form>           
                </Modal>

                <Modal
                    title="发送钉钉消息"
                    visible={visible_send_msg}
                    onCancel={this.onFinishMessageSendCancel}
                    okText="确认"
                    cancelText="取消"
                    footer={null}
                >
                    <Form
                        onFinish={this.onFinishMessageSend}
                        ref={this.formRefSendMsg}
                    >
                        <Form.Item label="消息ID" name="id" hidden style={myStyleForm}>
                            <Input ></Input>
                        </Form.Item>

                        <Form.Item label="消息名称" name="remark" rules={[{ required: true}]} style={myStyleForm}>
                            <Input disabled></Input>
                        </Form.Item>

                        <Form.Item label="消息内容" name="message" rules={[{ required: true}]} style={myStyleForm}>
                            <TextArea rows={20} disabled/>
                        </Form.Item>

                        <Form.Item label="消息群组" name="notify_admin_group_ids" rules={[{ required: true}]} style={myStyleForm}>
                            <Select
                                allowClear
                                showSearch
                                mode="multiple"
                                // style={{ width: 180 }}
                                placeholder="请选择消息群"
                                optionFilterProp="children"
                                onChange={this.onChangePlatform}
                                filterOption={(input, option) =>
                                    option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                }
                            >
                                {search_option_notify_admin_group}
                            </Select>
                        </Form.Item>

                        <Form.Item>
                            <Button htmlType="submit" type="primary">发送消息</Button>
                        </Form.Item>                                                               
                    </Form>           
                </Modal>

                <Modal
                    title="删除钉钉消息"
                    visible={visible_delete}
                    onOk={this.handleNotifyAdminGroupMessageDelete}
                    onCancel={() => {this.setState({visible_delete: false, message_id: ''})}}
                    okText="确认"
                    cancelText="取消"
                >
                    <p>确定删除消息? 删除后将无法恢复</p>
                </Modal>
            </Fragment>
        )
    }
}
export default NotifyAdminMessageManage;